package com.hksj.Intelligentmanagement.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hksj.Intelligentmanagement.common.Result;
import com.hksj.Intelligentmanagement.dto.DictChildDTO;
import com.hksj.Intelligentmanagement.dto.DictDTO;
import com.hksj.Intelligentmanagement.entity.DictEntity;
import com.hksj.Intelligentmanagement.mapper.DictMapper;
import com.hksj.Intelligentmanagement.vo.DictVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictService {
    @Autowired
    private DictMapper dictMapper;

    //新增字典表
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result addDict(DictDTO dictDTO) {
        QueryWrapper<DictEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("name", dictDTO.getName());
        Integer count = dictMapper.selectCount(wrapper);
        if (count > 0) {
            return Result.error("字典名称已存在");
        }
        DictEntity dictEntity = new DictEntity();
        BeanUtils.copyProperties(dictDTO, dictEntity);
        dictEntity.setHasChild(0);
        dictEntity.setPid("0");
        dictEntity.setLevel(1);
        dictEntity.setState("1");
        dictMapper.insert(dictEntity);
        List<DictChildDTO> list = dictDTO.getList();
        if (CollectionUtil.isNotEmpty(list)) {
            dictEntity.setHasChild(1);
            dictMapper.updateById(dictEntity);
            for (DictChildDTO childDTO : list) {
                //遍历list
                DictEntity dictEntity1 = new DictEntity();
                dictEntity1.setPid(dictEntity.getId());
                dictEntity1.setName(childDTO.getName());
                dictEntity1.setProperty(childDTO.getProperty());
                dictEntity1.setHasChild(0);
                dictEntity1.setState("1");
                dictEntity1.setLevel(2);
                //插入字典字段子项
                dictMapper.insert(dictEntity1);
            }
        }
        return Result.ok("新增字典完成");
    }

    //删除字典
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result deleteDict(String id) {
        //查询出对应父id的子项
        QueryWrapper<DictEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        //删除字典子项
        int insert = dictMapper.delete(wrapper);
        //删除字典父项
        int insert1 = dictMapper.deleteById(id);
        //一定有对应的子项吗
        if (insert <= 0 && insert1 <= 0) {
            return Result.error("删除失败");
        }
        return Result.ok("删除成功");
    }

    //更新字典
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result updateDict(DictDTO dictDTO) {
        //查询更新字典父项
        QueryWrapper<DictEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", dictDTO.getId());
        DictEntity dictEntity = dictMapper.selectById(dictDTO.getId());
        dictMapper.updateById(dictEntity);
        //字典子项list
        QueryWrapper<DictEntity> wrapper1 = new QueryWrapper<>();
        wrapper.eq("parent_id", dictDTO.getId());
        List<DictEntity> dictEntities = dictMapper.selectList(wrapper1);
        //拿到每一个子字典的id
        List<String> list = dictEntities.stream().map(DictEntity::getId).collect(Collectors.toList());
        //拿到前端传来的子字典的信息
        List<DictChildDTO> dictChildDTOS = dictDTO.getList();
        //获取到前端传来的子字典的id信息
        List<String> list1 = dictChildDTOS.stream().map(DictChildDTO::getDictChildId).collect(Collectors.toList());
        //取数据库中子字典 和 前端传来的子字典的id的交集并做更新
        ArrayList<String> list2 = new ArrayList<>(CollectionUtil.intersection(list, list1));
        //拿到需要做更新的DictChildDTO
        List<DictChildDTO> childDTOS = dictChildDTOS.stream()
                .filter(r -> list2.contains(r.getDictChildId())).collect(Collectors.toList());
        //对数据库进行更新
        for (DictChildDTO dto : childDTOS) {
            DictEntity dictEntity1 = new DictEntity();
            dictEntity1.setId(dto.getDictChildId());
            dictEntity1.setPid(dictDTO.getId());
            dictEntity1.setName(dto.getName());
            dictEntity1.setProperty(dto.getProperty());
            //dictEntity1.setLevel(dto.getLevel());
            //dictEntity1.setHasChild(0);
            //dictEntity1.setState("1");
            dictMapper.updateById(dictEntity1);
        }
        //前端传来的id为空，则在数据库中新增该记录
        List<DictChildDTO> dictChildDTOS1 = dictChildDTOS.stream()
                .filter(r -> StringUtils.isEmpty(r.getDictChildId()))
                .collect(Collectors.toList());
        //数据库新增该记录
        for (DictChildDTO dto : dictChildDTOS1) {
            DictEntity dictEntity2 = new DictEntity();
            dictEntity2.setId(dto.getDictChildId());
            dictEntity2.setPid(dictDTO.getId());
            dictEntity2.setName(dto.getName());
            dictEntity2.setProperty(dto.getProperty());
            dictEntity2.setLevel(2);
            dictEntity2.setState("1");
            dictEntity2.setHasChild(0);
            //插入新增的数据
            dictMapper.insert(dictEntity2);
        }
        //删除数据库中存在，但前端没有传来的值 取list2数据库中查到的子字典记录 和 list1前端传来的子字典记录的交集的补集
        ArrayList<String> subtractDeleteChildIds = new ArrayList<>(CollectionUtil.subtract(list, list1));
        if (CollectionUtil.isNotEmpty(subtractDeleteChildIds)) {
            //通过id批量删除
            dictMapper.deleteBatchIds(subtractDeleteChildIds);
        }
        //父字典更新
        DictEntity entity = new DictEntity();
        BeanUtils.copyProperties(dictDTO, entity);
        dictMapper.updateById(entity);
        return Result.ok("更新成功");
    }

    //分页查询字典
    public Result queryDictByPage(DictDTO dictDTO) {
        //创建分页实例
        Page<DictVo> page = new Page<>(dictDTO.getPageNum(), dictDTO.getPageSize());
        //查询父字典列表
        List<DictVo> dictVos = dictMapper.queryDictByPage(page, dictDTO);
        page.setRecords(dictVos);
        return Result.data(page);
    }

    //查询子字典
    public Result queryChildDictByPidId(String id) {
        //查询字典信息
        DictEntity dictEntity =dictMapper.selectById(id);
        //查询结果是否为空 判断id是否输入有错误
        if(ObjectUtil.isNotNull(dictEntity)) {
            //判断字典状态state是否启用
            if (dictEntity.getState().equals("1")) {
                //根据父id查询子字典的信息pid字段
                List<DictVo> dictVos = dictMapper.queryChildDictByPidId(id);
                    return Result.data(dictVos);
            }
        }
        return Result.error("查询到的父字典id输入有误");
    }

    //查询单个字典信息
    public Result queryDictById(String id) {
        DictEntity dictEntity=dictMapper.selectById(id);
        return Result.data(dictEntity);
    }
}
